import { createUniver, defaultTheme, LocaleType, LogLevel, merge } from '@univerjs/presets'
import { UniverSheetsConditionalFormattingPreset } from '@univerjs/presets/preset-sheets-conditional-formatting'
import sheetsConditionalFormattingZhCN from '@univerjs/presets/preset-sheets-conditional-formatting/locales/zh-CN'
import { UniverSheetsCorePreset } from '@univerjs/presets/preset-sheets-core'
import sheetsCoreZhCN from '@univerjs/presets/preset-sheets-core/locales/zh-CN'
import { UniverSheetsDataValidationPreset } from '@univerjs/presets/preset-sheets-data-validation'
import sheetsDataValidationZhCN from '@univerjs/presets/preset-sheets-data-validation/locales/zh-CN'
import { UniverSheetsDrawingPreset } from '@univerjs/presets/preset-sheets-drawing'
import sheetsDrawingZhCN from '@univerjs/presets/preset-sheets-drawing/locales/zh-CN'
import { UniverSheetsFilterPreset } from '@univerjs/presets/preset-sheets-filter'
import sheetsFilterZhCN from '@univerjs/presets/preset-sheets-filter/locales/zh-CN'
import { UniverSheetsHyperLinkPreset } from '@univerjs/presets/preset-sheets-hyper-link'
import sheetsHyperLinkZhCN from '@univerjs/presets/preset-sheets-hyper-link/locales/zh-CN'
import { WORKBOOK_DATA } from './data'
import { Upload, Button, message } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
// import { Univer } from '@univerjs/core'
import { read, utils } from 'xlsx'

import './UniverJs.css'
import '@univerjs/presets/lib/styles/preset-sheets-core.css'
import '@univerjs/presets/lib/styles/preset-sheets-conditional-formatting.css'
import '@univerjs/presets/lib/styles/preset-sheets-data-validation.css'
import '@univerjs/presets/lib/styles/preset-sheets-drawing.css'
import '@univerjs/presets/lib/styles/preset-sheets-filter.css'
import '@univerjs/presets/lib/styles/preset-sheets-hyper-link.css'
import {
  SetRangeBoldCommand /* ,InsertHyperlinkCommand,EditHyperlinkCommand,RemoveHyperlinkCommand */
} from '@univerjs/sheets-ui'

import { useState, useRef, useEffect } from 'react'

export const UniverJs = () => {
  const containerRef = useRef<HTMLDivElement>(null)

  const [loading, setLoading] = useState(false)

  // 处理文件上传
  const handleFileUpload = async (file: File) => {
    setLoading(true)
    try {
      const arrayBuffer = await file.arrayBuffer()
      const workbook = read(new Uint8Array(arrayBuffer), { type: 'array' })
      const sheetData = utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], { header: 1 })
      console.log('workbook', workbook)
      console.log('sheetData', sheetData)

      function convertMultiSheetsToUniver(excelSheetsData, workbookId = 'workbook-1') {
        const sheets = {}
        const sheetOrder: [] = []
        // 遍历每个分类（工作表）
        Object.keys(excelSheetsData).forEach((sheetName, index) => {
          const sheetId = `sheet-${index + 1 < 10 ? '0' + (index + 1) : index + 1}` // 生成唯一ID（如需要 UUID 可替换）
          const sheetsData = excelSheetsData[sheetName]
          sheetOrder.push(sheetId)
          // 构建当前工作表的 cellData
          const cellData = {}
          for (let row = 0; row < sheetData.length; row++) {
            cellData[row] = {}
            for (let col = 0; col < sheetData[row].length; col++) {
              cellData[row][col] = {
                v: sheetData[row][col] // 原始值
                // 可选：添加样式（如字体、颜色等）
                // s: { fontFamily: "Arial", fontSize: 12 }
              }
            }
          }
          // 构造单个工作表配置
          sheets[sheetId] = {
            id: sheetId,
            name: sheetName,
            rowCount: sheetsData.length,
            columnCount: sheetsData[0]?.length || 0,
            tabColor: '',
            hidden: 0,
            zoomRatio: 1,
            scrollTop: 0,
            scrollLeft: 0,
            defaultColumnWidth: 73,
            defaultRowHeight: 19,
            mergeData: [
              {
                startRow: 14,
                endRow: 14,
                startColumn: 2,
                endColumn: 3
              },
              {
                startRow: 15,
                endRow: 18,
                startColumn: 10,
                endColumn: 12
              }
            ],
            cellData: cellData,
            rowData: {
              0: {
                hd: 0,
                h: 19
              },
              1: {
                hd: 0,
                h: 19
              },
              2: {
                hd: 0,
                h: 19
              },
              3: {
                hd: 0,
                h: 19
              },
              4: {
                hd: 0,
                h: 19
              },
              5: {
                hd: 0,
                h: 36
              },
              6: {
                hd: 0,
                h: 19
              },
              7: {
                hd: 0,
                h: 19
              },
              8: {
                hd: 0,
                h: 19
              },
              9: {
                hd: 0,
                h: 19
              },
              10: {
                hd: 0,
                h: 19
              },
              11: {
                hd: 0,
                h: 19
              },
              12: {
                hd: 0,
                h: 19
              },
              13: {
                hd: 0,
                h: 19
              },
              14: {
                hd: 0,
                h: 19
              },
              15: {
                hd: 0,
                h: 19
              },
              16: {
                hd: 0,
                h: 19
              },
              17: {
                hd: 0,
                h: 28,
                ah: 19,
                ia: 0
              },
              18: {
                hd: 0,
                h: 19
              },
              19: {
                hd: 0,
                h: 21,
                ia: 0
              },
              20: {
                hd: 0,
                h: 19
              },
              21: {
                hd: 0,
                h: 19,
                ah: 19
              },
              22: {
                hd: 0,
                h: 19
              },
              23: {
                hd: 0,
                h: 19,
                ah: 19
              },
              24: {
                hd: 0,
                h: 19
              },
              25: {
                hd: 0,
                h: 67,
                ia: 0
              },
              26: {
                hd: 0,
                h: 19
              },
              27: {
                hd: 0,
                h: 19
              },
              28: {
                hd: 0,
                h: 19,
                ah: 48.8
              },
              29: {
                hd: 0,
                h: 60,
                ia: 0
              }
            },
            columnData: {
              0: {
                w: 130,
                hd: 0
              },
              1: {
                w: 80,
                hd: 0
              },
              2: {
                w: 130,
                hd: 0
              },
              3: {
                w: 130,
                hd: 0
              },
              4: {
                w: 130,
                hd: 0
              },
              5: {
                w: 130,
                hd: 0
              },
              6: {
                w: 130,
                hd: 0
              },
              7: {
                w: 130,
                hd: 0
              },
              8: {
                w: 130,
                hd: 0
              },
              9: {
                w: 130,
                hd: 0
              },
              10: {
                w: 130,
                hd: 0
              },
              11: {
                w: 73,
                hd: 0
              },
              12: {
                w: 73,
                hd: 0
              }
            },
            showGridlines: 1,
            rowHeader: {
              width: 46,
              hidden: 0
            },
            columnHeader: {
              height: 20,
              hidden: 0
            },
            rightToLeft: 0
          }
        })

        // 返回完整 UniverJS 工作簿数据
        return {
          id: workbookId,
          sheets: sheets,
          sheetOrder: sheetOrder, // 顺序与 Excel 的 SheetNames 一致
          locale: 'zhCN',
          resources: []
        }
      }

      // 使用示例
      const univerWorkbook = convertMultiSheetsToUniver(workbook.Sheets)
      univerWorkbook.sheets['sheet-01'] = {
        ...WORKBOOK_DATA.sheets['sheet-01'],
        cellData: univerWorkbook.sheets['sheet-01'].cellData
      }

      console.log('univerWorkbook', univerWorkbook)

      const { univerAPI } = createUniver({
        logLevel: LogLevel.VERBOSE,
        locale: LocaleType.ZH_CN,
        locales: {
          [LocaleType.ZH_CN]: merge(
            {},
            sheetsCoreZhCN,
            sheetsConditionalFormattingZhCN,
            sheetsDataValidationZhCN,
            sheetsDrawingZhCN,
            sheetsFilterZhCN,
            sheetsHyperLinkZhCN
          )
        },
        theme: defaultTheme,
        presets: [
          UniverSheetsCorePreset({
            container: 'UniverJs',
            header: true,
            toolbar: true,
            footer: true,
            contextMenu: true,
            disableAutoFocus: true,
            menu: {
              // 粗体
              [SetRangeBoldCommand.id]: {
                hidden: false
              },
              // 超链接
              'sheet.operation.insert-hyper-link-toolbar': {
                hidden: true
              },
              //  保护行列（工具栏按钮）
              'sheet.command.add-range-protection-from-toolbar': {
                hidden: true
              },

              //  新增保护行列（菜单右键）
              'sheet.command.add-range-protection-from-context-menu': {
                hidden: true
              },
              // 查看所有保护范围（菜单右键）
              'sheet.command.view-sheet-permission-from-context-menu': {
                hidden: true
              },
              // 移除保护范围（菜单右键）
              'sheet.command.delete-range-protection-from-context-menu': {
                hidden: true
              },

              //  快捷键面板
              'base-ui.operation.toggle-shortcut-panel': {
                hidden: true
              },
              // 货币
              'sheet.command.numfmt.set.currency': {
                hidden: true
              }
            }
          }),
          UniverSheetsConditionalFormattingPreset(),
          UniverSheetsDataValidationPreset(),
          UniverSheetsDrawingPreset(),
          UniverSheetsFilterPreset(),
          UniverSheetsHyperLinkPreset()
        ]
      })

      univerAPI.createWorkbook(univerWorkbook)

      message.success('文件加载成功')
    } catch (error) {
      console.log(error)

      message.error('文件解析失败')
    } finally {
      setLoading(false)
    }
    return false
  }

  useEffect(() => {
    const { univerAPI } = createUniver({
      logLevel: LogLevel.VERBOSE,
      locale: LocaleType.ZH_CN,
      locales: {
        [LocaleType.ZH_CN]: merge(
          {},
          sheetsCoreZhCN,
          sheetsConditionalFormattingZhCN,
          sheetsDataValidationZhCN,
          sheetsDrawingZhCN,
          sheetsFilterZhCN,
          sheetsHyperLinkZhCN
        )
      },
      theme: defaultTheme,
      presets: [
        UniverSheetsCorePreset({
          container: 'UniverJs',
          header: true,
          toolbar: true,
          footer: true,
          contextMenu: true,
          disableAutoFocus: true,
          menu: {
            // 粗体
            [SetRangeBoldCommand.id]: {
              hidden: false
            },
            // 超链接
            'sheet.operation.insert-hyper-link-toolbar': {
              hidden: true
            },
            //  保护行列（工具栏按钮）
            'sheet.command.add-range-protection-from-toolbar': {
              hidden: true
            },

            //  新增保护行列（菜单右键）
            'sheet.command.add-range-protection-from-context-menu': {
              hidden: true
            },
            // 查看所有保护范围（菜单右键）
            'sheet.command.view-sheet-permission-from-context-menu': {
              hidden: true
            },
            // 移除保护范围（菜单右键）
            'sheet.command.delete-range-protection-from-context-menu': {
              hidden: true
            },

            //  快捷键面板
            'base-ui.operation.toggle-shortcut-panel': {
              hidden: true
            },
            // 货币
            'sheet.command.numfmt.set.currency': {
              hidden: true
            }
          }
        }),
        UniverSheetsConditionalFormattingPreset(),
        UniverSheetsDataValidationPreset(),
        UniverSheetsDrawingPreset(),
        UniverSheetsFilterPreset(),
        UniverSheetsHyperLinkPreset()
      ]
    })

    univerAPI.createWorkbook(WORKBOOK_DATA)

    return () => {
      univerAPI.dispose()
    }
  }, [])

  return (
    <div style={{ height: '100%' }}>
      <Upload accept=".xlsx,.xls" beforeUpload={handleFileUpload} showUploadList={false}>
        <Button icon={<UploadOutlined />} loading={loading}>
          {loading ? '加载中...' : '上传 Excel 文件'}
        </Button>
      </Upload>
      <div id="UniverJs" ref={containerRef} />
    </div>
  )
}
